package com.zx.util;

import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

public abstract class BeanCopyUtil {

    /**
     * @param source
     * @param from
     * @param to
     * @return
     * @Title: pojo类型转换
     * @date: 2020-8-18 19:36:53
     * @author: zhangxue01
     */
    public static <FROM, TO> TO copy(FROM source, Class<FROM> from, Class<TO> to) {
        try {
            // 调用无参构造函数创建对象
            TO instance = to.getConstructor().newInstance();
            BeanUtils.copyProperties(source, instance);
            return instance;
        } catch (Exception e) {
            throw new RuntimeException("convert exception", e);
        }
    }

    /**
     * @param source
     * @param from
     * @param to
     * @return
     * @Title: 集合类型转换
     * @date: 2020-8-18 19:36:53
     * @author: zhangxue01
     */
    public static <FROM, TO> List<TO> copy(List<FROM> source, Class<FROM> from, Class<TO> to) {
        List<TO> list = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(source)) {
            for (FROM fo : source) {
                try {
                    TO instance = to.newInstance();
                    BeanUtils.copyProperties(fo, instance);
                    list.add(instance);
                } catch (Exception e) {
                    throw new RuntimeException("convert exception", e);
                }
            }
        }
        return list;
    }


}